package com.woniuxy.log.rabbbitMQ.consumer;

import com.rabbitmq.client.Channel;
import com.woniuxy.commons.entity.Log;
import com.woniuxy.log.mapper.LogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 消费者，负责监听消息队列，消费消息
 */

@Component
@Slf4j
public class LogConsumer {
    @Resource
    private LogMapper logMapper;

    //指定监听那些队列
    @RabbitListener(queues = "log")
    public void consume(Channel channel, Message message, Log _log) throws IOException {
        log.info("log接收到：" + _log);
        try {
            // 保存日志
            logMapper.add(_log);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            e.printStackTrace();
        }
    }
}
